<template>
  <base-modal :width="modAlProps.width" :isVisible="props.isVisible" :title="modAlProps.title" :buttons="buttons"
    :isCancleBtn="props.modelType == 6 && !props.tokenStr ||props.modelType == 7 ||props.modelType == 8 ? false : true" @handleCancle="handleCancle" @handleOk="buttonMessage"
    class="move_modal">
    <template v-slot:body>
      <!-- 上传 -->
      <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
        ref="columnFrom">
        <a-form-item :label="props.modelType == 1 ? '选择模板方案' : '上传文件'" name="uploadFile"
          :rules="[{ required: true, trigger: 'blur', message: '请上传文件!' }]"
          v-if="props.modelType == 3 || props.modelType == 1">
          <div class="modelType3">
            <a-input v-model:value="formState.uploadFile" readonly></a-input>
            <a-form-item-rest>
              <a-upload :multiple="true" :show-upload-list="false" v-model:file-list="fileList"
                :custom-request="(file: otherType) => handleUpload(file)" :before-upload="beforeUpload">
                <div>
                  <a-button type="primary" class="upload_button_line">
                    <upload-outlined></upload-outlined>
                    选择文件
                  </a-button>
                </div>
              </a-upload>
            </a-form-item-rest>
          </div>
        </a-form-item>
        <!-- 导出 -->
        <a-form-item label="选择方案" name="relativePath" :rules="[{ required: true, trigger: 'change', message: '请选择方案!' }]"
          v-if="props.modelType == 2">
          <a-select v-model:value="formState.relativePath" :options="directoryData"></a-select>
        </a-form-item>
        <!-- 新建目录 -->
        <a-form-item label="新建目录" name="directoryName" :rules="[{ required: true, trigger: 'blur', message: '请输入目录名称!' }]"
          v-if="props.modelType == 4">
          <div class="modelType4">
            <a-input v-model:value="formState.directoryName"></a-input>
          </div>
        </a-form-item>
      </a-form>
      <!-- 查看引用 -->
      <div v-if="props.modelType == 5" class="modelType5">
        <div class="modelType5Box" v-for="item in referModelList">
          <div>
            <span>模型名称：</span>
            <span>{{ item.modelName }}</span>
          </div>
          <div>
            <span> 模型类型： </span>
            <!-- getRecordValue(text) -->
            <span> {{ getRecordValue(item.modelType) }} </span>
          </div>
        </div>
        <!-- referModelList -->
      </div>
      <!-- 下载模版 -->
      <div v-if="props.modelType == 6" class="modelType6">
        <div class="wxLogin" v-if="!props.tokenStr">
          <div class="login_container">
            <div id="login_container"></div>
          </div>
        </div>
        <!-- 模版表格展示部分 -->
        <baseTable v-else :columns="columns.lowTemplateColumns" :dataSource="lowcodeTempList" :isSelect="true"
          :scroll="scroll" ref="searchBaseTables" :isShowPagination="false" :showCheckDelete="false"
          disabledParam="status" :disabledValue="true">
          <template style="height: 200px" #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'tags'">
              <template v-for="(item, index) in record.tplLabels">
                <span style="margin-left: 3px;" v-if="index < 3">{{ item }}、</span>
              </template>
            </template>
          </template>
        </baseTable>
      </div>
      <!-- 上传编辑器 -->
      <div v-if="props.modelType == 8 || props.modelType == 7" class="modelType6">
        <div class="wxLogin">
          <div class="login_container">
            <div id="login_container"></div>
          </div>
        </div>
      </div>
      <!-- 下载 -->
      <a-form  v-if="props.modelType == 10" name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
        ref="columnFrom">
        <!-- 导出 -->
        <a-form-item label="请选择文件格式" name="relativePath">
          <a-radio-group v-model:value="exportFileValue">
            <a-radio :style="radioStyle" :value="1">原文件格式</a-radio>
            <a-radio :style="radioStyle" :value="2">藏茗山智能网页设计平台文件格式</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import baseTree from "@/components/tree/baseTree.vue";
import baseModal from "@/components/modal/baseModal.vue";
import { message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import { scrollType, dataSourceType, configDataType } from "@/type";
import getters from "@/store/getters";
import request from "@/api/index";
import { startState } from "codemirror";
import globalFun from "@/utils/global";
import type { UploadChangeParam, UploadProps } from "ant-design-vue";
import columns from "@/components/table/tableConfig/tableColumn/configTableColumn";
import { getTableScroll } from "@/components/table/tableConfig/table";
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  modelType: {
    type: Number,
    default: null,
  },
  relativePath: {
    type: String,
    default: "",
  },
  tokenStr: {
    type: String,
    default: null,
  },
  rowSelection: {
    type: Array,
    default: [],
  },
});
let buttons = ref<dataSourceType[]>([
  {
    text: "确定",
    "html-type": "submit",
    keepAlive: true,
  },
]);
const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
})
//模态框数据
const modAlProps = reactive<dataSourceType>({
  width: "M",
  title:
    props.modelType == 1
      ? "导入模板"
      : props.modelType == 2
        ? "导出模板"
        : props.modelType == 3
          ? "上传"
          : props.modelType == 4
            ? "新建目录"
            : props.modelType == 5 ? "查看引用" : props.modelType == 6 ? "下载模板"  : props.modelType == 7  ? "上传至编辑器" : props.modelType == 8 ? "可视化编辑" : props.modelType == 10 && "文件下载",
});
const getRecordValue = (key: number) => {
  return key == 1
    ? "栏目模型"
    : key == 2
      ? "内容模型"
      : key == 3
        ? "会员模型"
        : key == 4
          ? "职位模型"
          : key == 5 && "简历模型";
};
//interface
interface Options {
  [propName: string | number]: any;
}
//下拉结构数据
const fieldNames = reactive<dataSourceType>({
  title: "name",
  key: "relativePath",
});
const formState = ref<dataSourceType>({
  uploadFile: [],
  directoryName: "",
  relativePath: "",
});
type otherType = {
  [propName: string]: any;
};

// data
const exportFileValue = ref<number>(1);
const fileList = ref([]);
const params = ref();
const treeData = ref<Options[]>([]);
const directoryData = ref<Options[]>([]);
// 低代码模版列表
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const lowcodeTempList = ref<Options>([])
const searchBaseTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
// computed
rowSelection = computed(() => {
  return searchBaseTables.value?.selectedRowKeys;
});

const userInfo = getters.userInfo();
const columnFrom = ref<any>("columnFrom");
const referModelList = ref<dataSourceType>([]);
const emits = defineEmits(["handleOk", "handleCancle"]);
const checked_Keys = (obj: dataSourceType) => {
  console.log(obj, "obj");
};

// watch
watch(() => rowSelection.value, (newVal: any) => {
  // console.log(newVal.length);
  if(newVal.length > 5) {
    searchBaseTables.value.selectedRowKeys = searchBaseTables.value.selectedRowKeys.splice(0,5,null)
    message.error('单次下载最大勾选5条模板！')
  }
})

const buttonMessage = async (msg: dataSourceType) => {
  columnFrom.value
    .validate()
    .then(() => {
      if (props.modelType == 1) {
        request
          .fetchTemplateBatchImport(params.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              emits("handleOk", msg);
              message.success(res.data.message);
            } else {
              message.error(res.data.message);
            }
          })
          .catch((err: any) => {
            console.log(err, 9999);
          });
      } else if (props.modelType == 2) {
        request
          .fetchTemplateBatchExport({
            relativePath: formState.value.relativePath,
          })
          .then((res: any) => {
            console.log(res, "sdfsdafasd");
            globalFun.downloadFile(res, res["content-disposition"]);
            emits("handleOk");
          })
          .catch((err: any) => {
            console.log(err, 9999);
          });
      } else if (props.modelType == 3) {
        console.log(fileList.value,'fileList.value')
        fileList.value.forEach((item:any) => {
          const param = new FormData();
        param.append("relativePath", `${props.relativePath || ""}`);
        param.append("uploadFile", item.originFileObj, item.originFileObj.name);
        params.value = param;
        request
          .fetchTemplateUploadFile(params.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              // emits("handleOk", msg);
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            console.log(err, 9999);
          });
        })
          emits("handleOk", msg);
      } else if (props.modelType == 4) {
        request
          .fetchTemplateAddDirectory({
            parentRelativePath: props.relativePath,
            directoryName: formState.value.directoryName,
          })
          .then((res: any) => {
            if (res.code == "00000 00000") {
              emits("handleOk", msg);
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            console.log(err, 9999);
          });
      } else if (props.tokenStr) { // 下载模版
        if (!rowSelection.value.length) {
          return message.error('请先勾选需要下载的模版！')
        }
        let keys: (string | number)[] = rowSelection.value;
        const params = {
          lowCodeToken: props.tokenStr,
          tplIds: keys,
          templateDir: localStorage.relativePath.split('/')[1],
        }
        console.log(params,'params');
        request.downloadTpls(params).then((res: any) => {
          if (res.code === "00000 00000") {
            message.success(res.message)
            rowSelection.value = searchBaseTables.value.selectedRowKeys = [];
            emits("handleOk");
          } else {
            message.error(res.message)
          }
        }).catch((err: any) => {
          throw new Error(err)
        })
      }else if (props.modelType == 10) { // 下载
        const params = {
          tplPaths: props.rowSelection,
          type: exportFileValue.value,
        }
        console.log(params,'params')
        request
          .downloadTpls(params)
          .then((res: any) => {
            globalFun.downloadFile(res, res["content-disposition"]);
            emits("handleOk");
          })
          .catch((err: any) => {
            console.log(err, 9999);
          });
      }
    })
    .catch(() => { });
};

const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
let acceptTypeList = ref<string[]>([]);
// 上传限制
const beforeUpload = (file: otherType["fileList"][number]) => {
  if (props.modelType == 1) {
    // 文件上传之前的限制条件过滤，有文件类型和文件大小限制。
    return new Promise((resolve, reject) => {
      // beforeUpload必须使用promise 返回false才能阻止change事件，否则无效
      const backgFix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取文件的后缀
      let isFileType = true;
      if (acceptTypeList.value.length) {
        isFileType = acceptTypeList.value.includes(backgFix);

        if (!isFileType) {
          message.error(`只能上传zip格式文件!`);
          return false;
        }
      }

      // let isLt2M = true;
      // if (props.isLimit) {
      //   isLt2M =
      //     props.isLimit == 0 ? true : file.size / 1024 / 1024 < props.isLimit;
      //   if (!isLt2M) {
      //     message.error(`文件大小不得超过 ${props.isLimit} MB!`);
      //     return false;
      //   }
      // }

      if (isFileType) {
        //fileList.value = [...fileList.value, file]
        return resolve(true);
      }
    });
  }
};
acceptTypeList = computed({
  get() {
    return ["zip"];
  },
  set() { },
});
// 上传
const handleUpload = (options: otherType) => {
  // console.log(options, "options");
  const param = new FormData();
  formState.value.uploadFile.push(options.file.name);
  if(props.modelType == 1) {
  param.append("relativePath", `${props.relativePath || ""}`);
  param.append("uploadFile", options.file, options.file.name);
  params.value = param;
  }
  // //
  // param.append("relativePath", `${props.relativePath || ""}`);
  // param.append("uploadFile", options.file, options.file.name);
  // params.value = param;
};

// 导出下拉接口
const fetchTemplateFolderList = async () => {
  let data = await request.fetchTemplateFolderList();
  directoryData.value = data?.map((item: any) => {
    let obj = {
      value: item,
      label: item,
    };
    return obj;
  });
  formState.value.relativePath = directoryData.value[0].label
  // dataList.push(...treeData.value);
};
// 查看引用接口
const fetchTemplateReferModelList = async () => {
  referModelList.value =
    (await request.fetchTemplateReferModelList({
      relativePath: props.relativePath,
    })) || [];
  // dataList.push(...treeData.value);
};
// 微信扫码
const initWx = () => {
  let path = window.location.origin
  let redirect_uri = ''
  if(path.includes('admin')) {
    redirect_uri = "http://vtest.jeecms.com/console/index.html"
  } else {
    redirect_uri = "http://v.jeecms.com/console/index.html"
  }
      let obj = new WxLogin({
        self_redirect: false,
        id: "login_container",
        appid: "wxbad43f79c9f07882",
        scope: "snsapi_login",
        redirect_uri: redirect_uri,
        state: true,
        style: "",
        href: "",
      });
      console.log(obj, 'initWxObj');
      // buttons.value = [{}]
};
// 获取低代码模版列表
const getTempList = () => {
  // 模拟数据
  // lowcodeTempList.value = [
  //   {id: 6, tplName: '这个是模版名称', tplLabels:['标签1','标签2','标签3']},
  // ]
  
  request.downloadTempList({ lowCodeToken: props.tokenStr }).then((res: any) => {
    console.log(res,'专题模版列表数据');

    lowcodeTempList.value = res || []
  }).catch((err: any) => {
    throw new Error(err)
  })
};


//onmounted
onMounted(async () => {
  switch (props.modelType) {
    case 2:
      fetchTemplateFolderList();
      break;
    case 5:
      fetchTemplateReferModelList();
      break;
    case 6: props.tokenStr ? getTempList() : initWx();
      break;
      case 7: initWx();
      break;
      case 8: initWx();
      break;
  }
});
</script>

<style lang="scss" scoped>
.move_modal {
  display: flex;

  span {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 28px;
  }

  span:first-child {
    width: 70px;
    text-align: right;
  }

  .openorclose {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 32px;

    .iconfont {
      margin-left: 5px;
      color: rgba(0, 0, 0, 0.85);
    }
  }

  .modelType3 {
    display: flex;
  }

  .modelType5 {
    .wxLogin {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 576px;
      height: 385px;
    }

    // display: flex;
    .modelType5Box {
      display: flex;
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;

      >div {
        width: 50%;

        span:first-child {
          // margin-right: 12px;
        }
      }
    }
  }

  .modelType6 {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

:deep(.ant-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.ant-table-cell:nth-last-child(1)) {
  text-align: right;
}

::v-deep(.ant-table-body) {
  max-height: 500px;
}
</style>
